package com.cskaoyan.user.service.impl;


import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.AddressConverter;
import com.cskaoyan.user.dal.entitys.Address;
import com.cskaoyan.user.dal.persistence.AddressMapper;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.form.UpdateAddressRequest;
import com.cskaoyan.user.service.IAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Slf4j
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    AddressConverter converter;

    @Override
    public List<AddressDto> addressList(Long uid) {
        Example example = new Example(Address.class);

        example.createCriteria().andEqualTo("userId", uid);
        List<Address> addresses = addressMapper.selectByExample(example);

        // 如果要在前端实现，自动选中默认地址的效果那么我们必须保证，默认地址在地址列表中的第一个位置
        int defaultIndex = -1;
        for (int i = 0; i < addresses.size(); i++) {
            if (addresses.get(i).getIsDefault()!= null && addresses.get(i).getIsDefault() == 1) {
                defaultIndex = i;
                break;
            }
        }

        if (defaultIndex != -1) {
            Address defaultAddress = addresses.remove(defaultIndex);
            addresses.add(0, defaultAddress);
        }
        List<AddressDto> addressDtos = converter.address2List(addresses);
        return addressDtos;
    }

    @Override
    public AddressDto addressDetail(Long addressId) {
        Address address = addressMapper.selectByPrimaryKey(addressId);
        AddressDto addressDto = converter.address2List(address);
        return addressDto;

    }

    @Override
    public void createAddress(AddAddressRequest request) {
        log.info("AddressServiceImpl.createAddress request :" + request);
        checkAddressDefaultUnique(request.getIsDefault() != null && request.getIsDefault(), request.getUserId());
        Address address = converter.req2Address(request);
        int row = addressMapper.insert(address);
        log.info("AddressServiceImpl.createAddress effect row :" + row);
    }

    @Override
    public void updateAddress(UpdateAddressRequest request) {
        log.error("begin - AddressServiceImpl.updateAddress request :" + request);
        checkAddressDefaultUnique(request.getIsDefault() != null && request.getIsDefault(), request.getUserId());
        Address address = converter.req2Address(request);
        int row = addressMapper.updateByPrimaryKey(address);
        log.info("AddressServiceImpl.createAddress effect row :" + row);
    }

    @Override
    public void deleteAddress(Long addressId) {
        log.error("begin - AddressServiceImpl.deleteAddress request :" + addressId);
        int row = addressMapper.deleteByPrimaryKey(addressId);
        if (row <= 0) {
            throw new ValidateException(UserRetCode.ADDRESS_ID_NOT_EXSITS.getCode(),
                    UserRetCode.ADDRESS_ID_NOT_EXSITS.getMessage());
        }
        log.info("AddressServiceImpl.deleteAddress effect row :" + row);

    }

    //地址只能有一个默认
    private void checkAddressDefaultUnique(boolean isDefault, Long userId) {
        if (isDefault) {
            Example example = new Example(Address.class);
            example.createCriteria().andEqualTo("userId", userId);
            List<Address> addresses = addressMapper.selectByExample(example);
            addresses.parallelStream().forEach(address -> {
                if (address.getIsDefault()!= null && address.getIsDefault() == 1) {
                    address.setIsDefault(0);
                    addressMapper.updateByPrimaryKey(address);
                }
            });
        }
    }
}
